import { useLocation, Navigate } from "react-router-dom";
import { axiosCanceler } from "@/api/helper/axiosCancel";
import { rootRouter } from "@/routes";
import { searchRoute, getRouterPathArray } from "@/utils/utils";
import { useSelector } from "@/store/hooks";

export default (props: { children: JSX.Element }) => {
	const { pathname } = useLocation();
	const { token } = useSelector(state => state.global);

	//在跳转理由前清空所有request请求
	axiosCanceler.removeAllPending();

	const currentRoute = searchRoute(pathname, rootRouter);
	//判断当前路由是否需要访问权限(不需要权限直接放行)
	if (Object.keys(currentRoute).length && !currentRoute.meta?.requiresAuth) return props.children;

	//判断是否有token,没有token直接去登录页面
	if (!token) return <Navigate to={"/user/login"} replace={true} />;

	//如果访问的地址没有在路由表中重定向到403页面（如果是动态路由需要从接口数据获取）
	if (getRouterPathArray(rootRouter).indexOf(pathname) === -1) return <Navigate to={"/403"} replace={true} />;

	//当前账号有权限返回 Router，正常访问页面
	return props.children;
};
